import {createRouter, createWebHistory, Router} from 'vue-router'
import {routes} from '@/router/routes'
import {ums_menulist} from '@/api/ums'
import useMenuStore from '@/store/useMenuStore'
import {UmsparentListRes} from '@/type/ums'
const router:Router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const store = useMenuStore()
  const a = from
  const token: string = sessionStorage.getItem("token")!
  if (token) {
    if (store.menu.length){
      if (to.name === 'login') {
        next("/home")
      }else {
        next()
      }
    }else {
      ums_menulist().then(res => {
        store.setMenu(res.data)
        function formRoute (arr:UmsparentListRes[], name?:string) {
          for (const item of arr) {
            const lastIndex = item.menu_url.lastIndexOf('/');
            const result = item.menu_url.substring(lastIndex + 1);
            const modules = import.meta.glob('../view/**/*.vue')
            const route = {
              name: result,
              path: item.menu_url,
              meta: {
                title: item.menu_name
              },
              component: modules['../view/'+item.menu_path+'.vue']
            }
            if (!router.hasRoute(route.name)){
              if (item.parent_id === '0'){
                if (item.menu_name === '首页') {
                  router.addRoute('layout', route)
                }else{
                  router.addRoute(route)
                }
              }else {
                router.addRoute(name!, route)
              }
            }
            if (item.children?.length){
              formRoute(item.children, result)
            }
          }
        }
        formRoute(res.data)
        if (to.name === 'login') {
          // next("/home")
          next('/shopping/product')
        }else {
          // next()
          next({ ...to, replace: true })
        }
      })
    }
  } else {
    if (to.name === 'login') {
      next()
    }else {
      next('/login')
    }
  }
})

router.afterEach((to, from, failure) => {
  document.title = to.meta.title!
})

export default router
